package daam.main;

import java.util.HashMap;

import android.content.Context;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Vibrator;

public class EffectThread extends Thread {
	
	private Game game;
	
	private final static int VIBRATE_TIME = 100;

	private SoundPool soundPool;
	private HashMap<Object,Object> soundPoolMap;
	private Vibrator vibrator;
	private final static int EAT_SOUND = 1;
	private final static int BOMBA_SOUND = 2;
	private final static int HEART_SOUND = 3;
	
	public EffectThread(Game game) {
		this.game = game;
		
		vibrator = (Vibrator) game.getSystemService(game.VIBRATOR_SERVICE);
		
		initSounds();
	
	}
	
	private void initSounds() {
		
		soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

		soundPoolMap = new HashMap<Object,Object>();

		soundPoolMap.put(EAT_SOUND, soundPool.load(game, R.raw.eat, 1));
		soundPoolMap.put(BOMBA_SOUND, soundPool.load(game, R.raw.bomb, 1));
		soundPoolMap.put(HEART_SOUND, soundPool.load(game, R.raw.heart, 1));
		
	}
	
	private void playSound(int sound) {

		AudioManager mgr = (AudioManager)game.getSystemService(game.AUDIO_SERVICE);

		float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
		float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
		float volume = streamVolumeCurrent / streamVolumeMax;
		
		soundPool.play((Integer) soundPoolMap.get(sound), volume, volume, 1, 0, 1); 

	}

	private void vibrar() {
		vibrator.vibrate(200);
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {}
		vibrator.vibrate(200);		
	}
	
	public void run(){
		
		while(game.getGameState()){
			
			if(game.playMusicFruit()){
				playSound(EAT_SOUND);
				game.setPlayMusicFruit(false);
			}
			
			if(game.playMusicHeart()){
				playSound(HEART_SOUND);
				game.setPlayMusicHeart(false);
			}
				
			if(game.playMusicBomb()){
				playSound(BOMBA_SOUND);
				game.setMusicBomb(false);
				
			}
			
			if(game.getvibrar())
				vibrar();
				game.setVibrar(false);
		}
	}

}
